<template>
  <div class="filter-card">
    <div class="filter-actions-row">
      <el-checkbox v-model="myOnly" @change="handleMyOnlyChange">
        我的需求
      </el-checkbox>
      <div class="filter-actions">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <div class="filter-search-row">
      <el-input
        v-model="localFilters.search"
        placeholder="搜索需求标题、描述、编号..."
        clearable
        class="filter-search"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="filter-item">
      <label>需求状态</label>
      <el-select
        v-model="localFilters.status"
        placeholder="请选择状态"
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="option in statusOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>优先级</label>
      <el-select
        v-model="localFilters.priority"
        placeholder="请选择优先级"
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="option in priorityOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>需求类型</label>
      <el-select
        v-model="localFilters.requirement_type"
        placeholder="请选择需求类型"
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="option in typeOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>需求来源</label>
      <el-select
        v-model="localFilters.source"
        placeholder="请选择需求来源"
        clearable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="option in sourceOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>

    <div class="filter-item">
      <label>负责人</label>
      <el-select
        v-model="localFilters.assignee_id"
        placeholder="请选择负责人"
        clearable
        filterable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="user in users"
          :key="user.id"
          :label="user.name || user.username"
          :value="user.id"
        >
          <UserDisplay
            :user="user"
            :show-avatar="true"
            size="small"
          />
        </el-option>
      </el-select>
    </div>

    <div class="filter-item">
      <label>报告人</label>
      <el-select
        v-model="localFilters.reporter_id"
        placeholder="请选择报告人"
        clearable
        filterable
        @change="handleImmediateChange"
      >
        <el-option
          v-for="user in users"
          :key="user.id"
          :label="user.name || user.username"
          :value="user.id"
        >
          <UserDisplay
            :user="user"
            :show-avatar="true"
            size="small"
          />
        </el-option>
      </el-select>
    </div>

    <div class="filter-item">
      <label>版本关联</label>
      <el-select
        v-model="hasVersion"
        placeholder="全部"
        clearable
        @change="handleHasVersionChange"
      >
        <el-option label="全部" value="all" />
        <el-option label="已关联版本" value="linked" />
        <el-option label="未关联版本" value="unlinked" />
      </el-select>
    </div>

    <div class="filter-item">
      <label>创建时间</label>
      <el-date-picker
        v-model="createdRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        unlink-panels
        style="width: 100%"
        @change="handleDateRangeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { RequirementFilters } from '@/stores/requirements'
import type { ProjectResponse } from '@/api/project'
import type { User } from '@/types/user'
import UserDisplay from '@/components/ui/UserDisplay.vue'

const props = defineProps<{
  filters: RequirementFilters
  projects: ProjectResponse[]
  users: User[]
  statusOptions: Array<{ value: string; label: string }>
  priorityOptions: Array<{ value: string; label: string }>
  typeOptions: Array<{ value: string; label: string }>
  sourceOptions: Array<{ value: string; label: string }>
  currentUserId?: string
}>()

const emit = defineEmits<{
  (event: 'apply', filters: Partial<RequirementFilters>): void
  (event: 'reset'): void
}>()

const localFilters = reactive<RequirementFilters>({ ...props.filters })
const createdRange = ref<[string, string] | []>([])
const hasVersion = ref<string | undefined>(undefined)

const myOnly = ref(false)

watch(
  () => props.filters,
  value => {
    Object.assign(localFilters, value)
    if (value.created_start && value.created_end) {
      createdRange.value = [value.created_start, value.created_end]
    } else {
      createdRange.value = []
    }
    if (typeof value.has_version === 'boolean') {
      hasVersion.value = value.has_version ? 'linked' : 'unlinked'
    } else {
      hasVersion.value = undefined
    }
    myOnly.value = Boolean(props.currentUserId && value.assignee_id === props.currentUserId)
  },
  { deep: true, immediate: true }
)

const handleSearch = () => {
  emit('apply', { ...localFilters })
}

const handleReset = () => {
  createdRange.value = []
  hasVersion.value = undefined
  myOnly.value = false
  emit('reset')
}

const handleImmediateChange = () => {
  // 当负责人选择改变时，同步更新"我的需求"复选框状态
  if (props.currentUserId) {
    myOnly.value = localFilters.assignee_id === props.currentUserId
  } else {
    myOnly.value = false
  }
  emit('apply', { ...localFilters })
}

const handleMyOnlyChange = (val: boolean | string | number) => {
  const checked = Boolean(val)
  // 检查 currentUserId 是否存在且不为空字符串
  if (checked && props.currentUserId && typeof props.currentUserId === 'string' && props.currentUserId.trim() !== '') {
    // 勾选"我的需求"时，设置负责人为当前用户
    localFilters.assignee_id = props.currentUserId
    // 立即触发筛选，确保筛选条件被应用
    emit('apply', { 
      ...localFilters,
      assignee_id: props.currentUserId 
    })
  } else {
    // 取消勾选"我的需求"时，清空负责人筛选
    localFilters.assignee_id = undefined
    // 立即触发筛选，确保筛选条件被清除
    emit('apply', { 
      ...localFilters,
      assignee_id: undefined 
    })
  }
}

const handleHasVersionChange = (value: string | undefined) => {
  if (value === 'linked') {
    localFilters.has_version = true
  } else if (value === 'unlinked') {
    localFilters.has_version = false
  } else {
    localFilters.has_version = undefined
  }
  emit('apply', { ...localFilters })
}

const handleDateRangeChange = (value: [string, string] | []) => {
  if (Array.isArray(value) && value.length === 2) {
    localFilters.created_start = value[0]
    localFilters.created_end = value[1]
  } else {
    localFilters.created_start = undefined
    localFilters.created_end = undefined
  }
  emit('apply', { ...localFilters })
}
</script>

<style scoped lang="scss">
.filter-card {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #ebeef5;
}

.filter-actions-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
  margin-bottom: 4px;
}

.filter-actions {
  display: flex;
  gap: 8px;
  
  :deep(.el-button) {
    padding: 6px 12px;
    border-radius: 6px;
    font-weight: 500;
    font-size: 13px;
    transition: all 0.2s;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    }
  }
}

.filter-search-row {
  display: flex;
  margin-bottom: 4px;
  
  :deep(.el-input) {
    .el-input__wrapper {
      border-radius: 8px;
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }
}

.filter-search {
  flex: 1;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  
  label {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
    margin-bottom: 2px;
  }
  
  :deep(.el-select),
  :deep(.el-date-editor) {
    width: 100%;
    
    .el-input__wrapper {
      border-radius: 6px;
      transition: all 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }
  
  :deep(.el-checkbox) {
    .el-checkbox__label {
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }
  }
}

:deep(.el-checkbox) {
  .el-checkbox__input {
    .el-checkbox__inner {
      border-radius: 4px;
      transition: all 0.2s;
    }
  }
  
  &:hover .el-checkbox__inner {
    border-color: #409eff;
  }
}
</style>

